@file:Suppress("DEPRECATION")

package me.leon.ade

import android.accessibilityservice.AccessibilityService
import android.content.Context
import android.graphics.Color
import android.graphics.PixelFormat
import android.os.Build
import android.provider.Settings
import android.provider.Settings.Secure
import android.text.TextUtils.SimpleStringSplitter
import android.util.Log
import android.view.Gravity
import android.view.WindowManager
import android.view.accessibility.AccessibilityEvent
import android.widget.Button
import android.widget.LinearLayout

/**
 * @author : Leon Shih
 * @date : 2020/1/2 0002 11:13 e-mail : deadogone@gmail.com desc : 无障碍服务
 */
class Svc : AccessibilityService() {
    override fun onInterrupt() {
        // if needed
    }

    override fun onAccessibilityEvent(event: AccessibilityEvent?) {
        // if needed
    }

    override fun onCreate() {
        super.onCreate()

        val windowManager =
            applicationContext.getSystemService(Context.WINDOW_SERVICE) as WindowManager

        val mParams =
            WindowManager.LayoutParams().apply {
                flags =
                    (WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON or
                        WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or
                        WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL)
                gravity = Gravity.CENTER
                type =
                    when {
                        Build.VERSION.SDK_INT >= 26 ->
                            WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
                        Build.VERSION.SDK_INT < 21 -> WindowManager.LayoutParams.TYPE_PRIORITY_PHONE
                        Build.VERSION.SDK_INT < 24 -> WindowManager.LayoutParams.TYPE_TOAST
                        else -> WindowManager.LayoutParams.TYPE_SYSTEM_ALERT
                    }

                width = WindowManager.LayoutParams.WRAP_CONTENT
                height = WindowManager.LayoutParams.WRAP_CONTENT
                format = PixelFormat.TRANSLUCENT
            }

        val linearLayout = LinearLayout(this)
        linearLayout.orientation = LinearLayout.HORIZONTAL

        val recentBtn =
            Button(this).apply {
                setBackgroundColor(Color.TRANSPARENT)
                text = "最近任务"
                setOnClickListener {
                    Log.d("svc", "recent")
                    performGlobalAction(GLOBAL_ACTION_RECENTS)
                }
            }

        val homeBtn =
            Button(this).apply {
                setBackgroundColor(Color.TRANSPARENT)
                text = "桌面"
                setOnClickListener {
                    Log.d("svc", "home")
                    performGlobalAction(GLOBAL_ACTION_HOME)
                }
            }

        val backBtn =
            Button(this).apply {
                setBackgroundColor(Color.TRANSPARENT)
                text = "返回"
                setOnClickListener {
                    Log.d("svc", "backBtn")
                    performGlobalAction(GLOBAL_ACTION_BACK)
                }
                setOnLongClickListener {
                    windowManager.removeViewImmediate(linearLayout)
                    true
                }
            }

        linearLayout.addView(recentBtn)
        linearLayout.addView(homeBtn)
        linearLayout.addView(backBtn)

        windowManager.addView(linearLayout, mParams)
    }

    companion object {
        fun isAccessibilitySettingsOn(mContext: Context): Boolean {
            var accessibilityEnabled = 0
            val service = mContext.packageName + "/" + Svc::class.java.canonicalName
            try {
                accessibilityEnabled =
                    Secure.getInt(
                        mContext.applicationContext.contentResolver,
                        Secure.ACCESSIBILITY_ENABLED
                    )
                Log.v("svc", "accessibilityEnabled = $accessibilityEnabled")
            } catch (e: Exception) {
                Log.e(
                    "svc",
                    "Error finding setting, default accessibility to not found: " + e.message
                )
            }
            val mStringColonSplitter = SimpleStringSplitter(':')
            if (accessibilityEnabled == 1) {
                Log.v("svc", "***ACCESSIBILITY IS ENABLED*** -----------------")
                val settingValue: String? =
                    Settings.Secure.getString(
                        mContext.applicationContext.contentResolver,
                        Secure.ENABLED_ACCESSIBILITY_SERVICES
                    )
                if (settingValue != null) {
                    mStringColonSplitter.setString(settingValue)
                    while (mStringColonSplitter.hasNext()) {
                        val accessibilityService = mStringColonSplitter.next()
                        Log.v(
                            "svc",
                            "-------------- > accessibilityService :: $accessibilityService $service"
                        )
                        if (accessibilityService.equals(service, ignoreCase = true)) {
                            Log.v(
                                "svc",
                                "We've found the correct setting - accessibility is switched on!"
                            )
                            return true
                        }
                    }
                }
            } else {
                Log.v("svc", "***ACCESSIBILITY IS DISABLED***")
            }
            return false
        }
    }
}
